package com.inspiration.utils;

import cn.hutool.core.date.DateUtil;

import java.io.*;
import java.util.Date;

/**
 * @Author : Vincent.jiao
 * @Date : 2023/11/4 16:44
 * @Version : 1.0
 */
public class DbUtil {
    public static void main(String[] args) {
        exportDatabaseTool("127.0.0.1", "3306", "root", "123456", "inspiration",
                "D:\\wwwdev\\wizbank\\core\\main\\inspiration_library\\target\\backupDB"
                            + File.separator + DateUtil.format(new Date(), "yyyy-MM-dd"),
                "demo.sql");
    }

    /**
     * 备份数据库
     * @param ip
     * @param host
     * @param username
     * @param password
     * @param databaseName
     * @param savePath
     * @param fileName
     */
    public static String exportDatabaseTool(String ip,String host,String username,String password,String databaseName,String savePath,String fileName){
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        File saveFile = new File(savePath, fileName);
        try {
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }

            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(saveFile),"utf-8"));

//            String command = "mysqldump -u " + username + " -p" + password + " " + databaseName +" > " + savePath+fileName;
//            String command = " mysqldump -h "+ip+" -P " +host+" -u "+username+" -p "+password+" --default-character-set=utf8 " + databaseName;
            String command = " mysqldump -h"+ip+" -p"+host+" -u"+username+" -p"+password+" --default-character-set=utf8 "+databaseName;
            Process process = Runtime.getRuntime().exec(command);


            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(),"utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return saveFile.toString();
    }
}
